import { Menu, MenuItemOptions, Submenu, SubmenuOptions } from "@tauri-apps/api/menu";
import { open } from "@tauri-apps/plugin-dialog";
import { loadSctFile } from "../fileLoader/loadSctFile";
import { loadEseFile } from "../fileLoader/loadEseFile";
import { loadPrfFile } from "../fileLoader/loadPrfFile";
import { loadAsrFile } from "../fileLoader/loadAsrFile";
import { RenderData, resetRenderData } from "../classes/RadarRenderData";
import { ConnectionData } from "../classes/ConnectionData";
import { RadarScreen } from "../RadarCanvasDrawer";
import { loadServerFile } from "../fileLoader/loadServerFile";
import { isFetchingVatsimData, startVatsimDataFetchInterval, stopVatsimDataFetchInterval } from "../vatsimApi/data";
import { loadSymbologyFile } from "../fileLoader/loadSymbologyFile";
import { PluginData } from "../classes/ExternalPluginData";
import { TauriInvoker } from "./TauriInvoker";
import { error } from "@tauri-apps/plugin-log";

class TauriMenuController {
    async refresh() {
        const sub0 = await Submenu.new({
            text: '',
            items: [
                {
                    id: 'about',
                    text: '关于 OpenScope',
                    action: () => {
                        console.log('menu about preesed')
                    }
                },
                {
                    id: 'check update',
                    text: '检查更新',
                    action: () => {

                    }
                },
                {
                    text: '',
                    item: 'Separator'
                },
                {
                    id: 'setting',
                    text: '设置',
                    action: async () => {
                        TauriInvoker.createWindow({
                            label: 'Setting',
                            url: 'testPage.html'
                        });
                    }
                },
                {
                    text: '',
                    item: 'Separator'
                },
                {
                    text: '外部服务',
                    items: [
                        {
                            text: '配置外部服务'
                        }
                    ]
                },
                {
                    text: '',
                    item: 'Separator'
                },
                {
                    text: '退出 OpenScope'
                }
            ]
        });
        const sub1 = await Submenu.new({
            text: '服务器',
            items: [
                {
                    id: 'quick_connect',
                    text: '恢复连接'
                },
                {
                    id: 'connect_server',
                    text: '连接到服务器'
                },
                {
                    text: '读取Server.txt',
                    action: () => {
                        open({ filters: [{ extensions: ['txt'], name: 'Server file' }] }).then(uri => {
                            if (uri == null) return;
                            loadServerFile(uri).then(() => this.refresh());
                        });
                    }
                },
                {
                    text: '',
                    item: 'Separator'
                },
                {
                    text: isFetchingVatsimData() ? '停止读取vatsim-data' : '连接到vatsim-data',
                    action: () => {
                        if (isFetchingVatsimData()) {
                            stopVatsimDataFetchInterval();
                        } else {
                            startVatsimDataFetchInterval();
                        }
                        this.refresh();
                    }
                },
                {
                    text: '',
                    item: 'Separator'
                },
                {
                    text: '配置服务器列表'
                }
            ]
        });
        await sub1.append({
            text: '',
            item: 'Separator'
        })

        const fastConnect = await Submenu.new({
            text: '快速连接',
            items: []
        });
        if (ConnectionData.availablePredefinedServer.length > 0) {
            for (const server of ConnectionData.availablePredefinedServer) {
                await fastConnect.append({
                    text: `${server.name}: ${server.addr}`
                });
            }
        } else {
            await fastConnect.append({
                text: '不可用',
                enabled: false
            })
        }

        await sub1.append(fastConnect);
        const comm = await Submenu.new({
            text: '通讯频率',
            items: [
                {
                    text: '配置'
                }
            ]
        });
        const sub2 = await Submenu.new({
            text: '扇区',
            items: [
                {
                    text: '加载扇区',
                    items: [
                        {
                            text: '加载Sct扇区',
                            action: () => {
                                open({ filters: [{ extensions: ['sct', 'sct2'], name: 'Sector file' }] }).then(uri => {
                                    if (uri == null) return;
                                    loadSctFile(uri).then(() => RadarScreen.draw());
                                });
                            }
                        },
                        {
                            text: '加载Ese扇区',
                            action: () => {
                                open({ filters: [{ extensions: ['ese'], name: 'Ese file' }] }).then(uri => {
                                    if (uri == null) return;
                                    loadEseFile(uri).then(() => RadarScreen.draw());
                                });
                            }
                        },
                        {
                            text: '加载Prf扇区',
                            action: () => {
                                console.log('load prf')
                                open({ filters: [{ extensions: ['prf'], name: 'Prf file' }] }).then(uri => {
                                    if (uri == null) return;
                                    loadPrfFile(uri).then(() => RadarScreen.draw());
                                });
                            }
                        },
                        {
                            text: '加载Asr扇区',
                            action: () => {
                                open({ filters: [{ extensions: ['asr'], name: 'Asr file' }] }).then(uri => {
                                    if (uri == null) return;
                                    loadAsrFile(uri).then(() => RadarScreen.draw());
                                });
                            }
                        }
                    ]
                },
                {
                    text: '加载配置',
                    items: [
                        {
                            text: '加载Symbology',
                            action: () => {
                                open({ filters: [{ extensions: ['txt'], name: 'Symbol file' }] }).then(uri => {
                                    if (uri == null) return;
                                    loadSymbologyFile(uri).then(() => RadarScreen.draw());
                                });
                            }
                        }
                    ]
                },
                {
                    text: '',
                    item: 'Separator'
                },
                {
                    text: '从内存中卸载',
                    action: () => {
                        resetRenderData();
                        RadarScreen.draw()
                    }
                },
                {
                    text: '',
                    item: 'Separator'
                },
                {
                    text: '配置渲染项目',
                    action: () => {
                        console.log(RenderData.asr);
                    }
                },
                {
                    text: '',
                    item: 'Separator'
                },
                {
                    text: 'ES扇区列表'
                }
            ]
        });
        const pluginSubMenus: Array<SubmenuOptions | MenuItemOptions> = [
            {
                text: '打开插件目录',
                action: async () => {
                    await TauriInvoker.openPath(PluginData.pluginPath);
                },
            },
            {
                text: '重载插件',
                action: () => {
                    PluginData.init().then(() => {
                        this.refresh();
                    });
                }
            }
        ];
        for (const plugin of PluginData.plugins) {
            const pluginMenus = plugin.onAcquireMenu();
            if (pluginMenus.length > 0) {
                pluginSubMenus.push({
                    text: plugin.onAcquirePluginInformation().pluginName,
                    items: plugin.onAcquireMenu(),
                });
            }
        }
        const sub3 = await Submenu.new({
            text: '插件',
            items: pluginSubMenus,
        });
        const menu = await Menu.new({
            items: [sub0, sub1, comm, sub2, sub3]
        });
        try {
            await menu.setAsAppMenu();
        } catch (e) {
            error(`fail to set as app menu, ${e}`);
        }
    }
}

export const MenuController = new TauriMenuController();